﻿using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HYHY_Core.Enums;
using HYHY_Core.Tool.Token;
using HYQY_App.Admin_System.Interface;
using HYQY_App.Login.Interface;
using HYQY_Core.Entities.Common;
using HYQY_Core.Entities.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HYQY_App.Admin_System.Dtos.MenuAdminDto;

namespace HYQY_App.Admin_System.Service
{
    /// <summary>
    /// 菜单管理服务
    /// </summary>
    [ApiDescriptionSettings(ApiGroupEnumsCode.Management, Name = "MenuAdminService")]
    public class MenuAdminService : IDynamicApiController, ITransient, IMenuAdminService
    {

        /// <summary>
        /// sql
        /// </summary>
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 构造函数
        /// </summary>
        public MenuAdminService(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 获取菜单配置列表（左侧菜单）
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetMenuListOuput>> SelectMenuList()
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey();
            if (string.IsNullOrWhiteSpace(user.UserId))
            {
                throw Oops.Bah("未登录，无权限");
            }

            if (/*!string.IsNullOrEmpty(user.PermissionGroupId)*/ true)
            {
                List<GetMenuListOuput> firstLevelMenuList = new();

                // 获取菜单
                var menuConfigList = await _db.Queryable<Menus>()
                    .Where(t => t.EnableMark == true && t.IsDelete == false).ToListAsync();

                firstLevelMenuList = menuConfigList
                    .Where(t => t.Level == 1)
                    .OrderBy(t => t.Sort).Select(t => new GetMenuListOuput
                    {
                        Id = t.Id,
                        Name = t.Name,
                        Path = t.Path,
                        Icon = t.Icon,
                        Sort = t.Sort,
                        EnableMark = t.EnableMark,
                        // 递归获取子级
                        Children = GetLowerMenuInfoList(t.Level, t.Id, menuConfigList)
                    })
                    .OrderBy(t => t.Sort)
                    .ToList();

                return firstLevelMenuList;
            }
            else
            {
                throw Oops.Bah("请重新登录").StatusCode(401);
            }
        }

        /// <summary>
        /// 获取子级
        /// </summary>
        /// <param name="level"></param>
        /// <param name="id"></param>
        /// <param name="menuList"></param>
        /// <returns></returns>
        private List<GetMenuListOuput> GetLowerMenuInfoList(int level, int id, List<Menus> menuList)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey();

            var result = new List<GetMenuListOuput>();
            result = menuList
                .Where(t => t.Level == level + 1 && t.ParentId == id)
                .OrderBy(t => t.Sort).Select(t => new GetMenuListOuput
                {
                    Id = t.Id,
                    Name = t.Name,
                    Path = t.Path,
                    Icon = t.Icon,
                    Sort = t.Sort,
                    ParentId = t.ParentId==0?null:t.ParentId,
                    EnableMark = t.EnableMark,
                    Children = GetLowerMenuInfoList(t.Level, t.Id, menuList)
                }).ToList();

            return result;
        }

        /// <summary>
        /// 获取菜单列表（列表显示）
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetMenuListOuput>> SelectMenuList_Show()
        {
            List<GetMenuListOuput> firstLevelMenuList = new();
            // 获取菜单
            var menuConfigList = await _db.Queryable<Menus>().ToListAsync();

            firstLevelMenuList = menuConfigList
                .Where(t => t.Level == 1)
                .OrderBy(t => t.Sort).Select(t => new GetMenuListOuput
                {
                    Id = t.Id,
                    Name = t.Name,
                    Path = t.Path,
                    Icon = t.Icon,
                    Sort = t.Sort,
                    ParentId = t.ParentId == 0 ? null : t.ParentId,
                    EnableMark = t.EnableMark,
                    Children = GetLowerMenuInfoList(t.Level, t.Id, menuConfigList)
                }).ToList();

            firstLevelMenuList = firstLevelMenuList.OrderBy(it => it.Sort).ToList();

            return firstLevelMenuList;
        }

        /// <summary>
        /// 设置菜单是否启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseStatus> UpdateIsEnableMark(UpdateIsEnableMarkInput input)
        {
            // 获取操作用户的信息
            var user = TokenService.GetClaimKey();

            var menu = await _db.Queryable<Menus>()
                .FirstAsync(it => it.Id == input.Id) ?? throw Oops.Bah("菜单不存在");

            menu.EnableMark = input.IsEnableMark;
            menu.UpdateMan = user.UserName;
            menu.UpdateTime = DateTime.Now;

            int count = await _db.Updateable(menu).WhereColumns(it => it.Id)
                .UpdateColumns(it => new
                {
                    it.EnableMark,
                    it.UpdateTime,
                    it.UpdateMan
                }).ExecuteCommandAsync();
            if (count < 1)
            {
                throw Oops.Bah("设置失败");
            }
            return new ResponseStatus { Message = "设置成功！", StatusCode = 200 };
        }
    }
}
